(function (w) {
  var sk = new Array();
  var sf = new Map();
  var loading = false;
  w.hostpath = "../";
  var $ = jQuery.noConflict();
  var pageSetting = {
    virtualPath: "~/",
  };

  $.mask = function (elm) {
    if ($("#_mask_")[0]) return; // loading 已经存在, 直接等loading消失

    //mask div
    var maskDiv = $(
      '<div id="_mask_" style="position: fixed;left: 0;top: 0;width: 100%;height: 100%;z-index: 901;display: block;opacity: 0.4;background: #000;filter: Alpha(opacity=40)"></div>',
    );
    var maxHeight = Math.max($(window).height(), $(document.body).height());
    maskDiv.height(maxHeight);
    // elm[0].top = '50%';
    // elm[0].left = '50%';
    elm[0].style.zIndex = "902";

    $(document.body).append(maskDiv);
    $(document.body).append(elm);
  };

  $.unmask = function (elm) {
    $("#_mask_").remove();
    // 这里应该把元素放回到原来母元素中去
  };

  var Tool = function () {
    this.virtualPath = window.hostpath;
    this.AjaxLoadList = {};
    this.Init();
  };
  Tool.prototype = {
    Init: function () {
      this.Page = null; //当前页面
      this.debug = 0; //0:正式环境，1:PC测试
      // 加载新版反爬
      this.loadNewSignature();
    },

    //Ajax 请求
    ToAjax: function (
      url,
      data,
      error,
      success,
      showload,
      TimeOut,
      method,
      beforeSend,
      complete,
    ) {
      //是否有其它请求插入
      this.AjaxRd = parseInt(Math.random() * 100000, 10);
      var rd = this.AjaxRd;
      //超时设置
      if (TimeOut == null) {
        TimeOut = 120000;
      }
      //showload: [null:不显示进度条,0:显示进度条,1:显示进度条成功不消失]. 新增一个值，执行成功函数后取消进度条
      if (showload != null) {
        var timer = this.ShowLoad();
      }

      var hfCurrentHotel = $("#hfCurrentHotel");
      if (hfCurrentHotel.length > 0 && data) {
        data.CurrentHotel = hfCurrentHotel.val();
      }

      $.ajax({
        url: url + "?v=" + Math.random(),
        type: method || "post",
        contentType: "application/x-www-form-urlencoded;charset=utf-8;",
        dataType: "json",
        data: data,
        timeout: TimeOut,
        error: function (json, e) {
          //屏蔽由于刷新引起错误
          if (json["readyState"] == "0") return;
          tl.HideLoad(timer);
          error(json);
        },
        success: function (json) {
          if (showload == 0 || showload == 1) {
            tl.HideLoad(timer);
          }
          switch (json.Rcode) {
            case -300: //无权限
              window.location.href =
                "//" +
                document.domain +
                "/ebkovsassembly/message.html?msg=" +
                json.Msg;
              break;
            case -100: //错误
              if (showload == 2) tl.HideLoad(timer);
              window.location.href =
                "//" + document.domain + "/ebkovsassembly/message.html";
              break;
            case 100: //登录失效
              if (showload == 2) tl.HideLoad(timer);
              window.location.href =
                "//" + document.domain + "/ebkovsassembly/Login";
              break;
            case 200:
              if (json.Script) {
                eval(json.Script);
              }
              break;
            default:
              //正常
              if (showload == 2) {
                success(json, rd == tl.AjaxRd ? true : false, timer);
              } else {
                success(json, rd == tl.AjaxRd ? true : false);
              }
              break;
          }
        },
        beforeSend: function () {
          if (beforeSend != null && $.type(beforeSend) === "function") {
            beforeSend();
          }
        },
        complete: function () {
          if (complete != null && $.type(complete) === "function") {
            complete();
          }
        },
      });
    },
    IsIE: function () {
      var ms_ie = false;
      var ua = window.navigator.userAgent;
      var old_ie = ua.indexOf("MSIE ");
      var new_ie = ua.indexOf("Trident/");

      if (old_ie > -1 || new_ie > -1) {
        ms_ie = true;
      }
      return ms_ie;
    },
    ToCasAjax: function (
      url,
      data,
      error,
      success,
      showload,
      TimeOut,
      method,
      beforeSend,
      complete,
    ) {
      //是否有其它请求插入
      this.AjaxRd = parseInt(Math.random() * 100000, 10);
      var rd = this.AjaxRd;
      //超时设置
      if (TimeOut == null) {
        TimeOut = 120000;
      }
      //showload: [null:不显示进度条,0:显示进度条,1:显示进度条成功不消失]. 新增一个值，执行成功函数后取消进度条
      if (showload != null) {
        var timer = this.ShowLoad();
      }

      var hfCurrentHotel = $("#hfCurrentHotel");
      if (hfCurrentHotel.length > 0 && data) {
        data.CurrentHotel = hfCurrentHotel.val();
      }

      $.casAjax({
        url: url + "?v=" + Math.random(),
        type: method || "post",
        contentType: "application/x-www-form-urlencoded;charset=utf-8;",
        dataType: "json",
        data: data,
        timeout: TimeOut,
        error: function (json, e) {
          //屏蔽由于刷新引起错误
          if (json["readyState"] == "0") return;
          tl.HideLoad(timer);
          error(json);
        },
        success: function (json) {
          if (showload == 0 || showload == 1) {
            tl.HideLoad(timer);
          }
          switch (json.Rcode) {
            case -300: //无权限
              window.location.href =
                "/ebkovsassembly/message.html?msg=" + json.Msg;
              break;
            case -100: //错误
              if (showload == 2) tl.HideLoad(timer);
              window.location.href = "/ebkovsassembly/message.html";
              break;
            case 100: //登录失效
              if (showload == 2) tl.HideLoad(timer);
              window.location.href = "/ebkovsassembly/Login";
              break;
            case 200:
              if (json.Script) {
                eval(json.Script);
              }
              break;
            default:
              //正常
              if (showload == 2) {
                success(json, rd == tl.AjaxRd ? true : false, timer);
              } else {
                success(json, rd == tl.AjaxRd ? true : false);
              }
              break;
          }
        },
        beforeSend: function () {
          if (beforeSend != null && $.type(beforeSend) === "function") {
            beforeSend();
          }
        },
        complete: function () {
          if (complete != null && $.type(complete) === "function") {
            complete();
          }
        },
      });
    },
    //页面跳转
    ToPage: function (url) {
      window.location.href = url;
    },
    //页面跳转
    ToSubmit: function (url, data) {
      var fm = document.forms[0];
      fm.action = url;
      var el;
      for (var name in data) {
        el = $("#h" + name)[0];
        if (el) el.value = data[name];
        else
          $(fm).append(
            '<input type="hidden" id="h' +
              name +
              '" name="' +
              name +
              '" value="' +
              data[name] +
              '"/>',
          );
      }
      fm.submit();
    },
    //显示正在加载进度条
    ShowLoad: function (msg) {
      // 预载入图片
      if (!Tool._loadingImg) {
        Tool._loadingImg = new Image();
        Tool._loadingImg.src = "//pic.c-ctrip.com/ebooking/web/loading_50.gif";
      }

      // 延时进度条效果
      var timer = setTimeout(function (waitingText) {
        var currentLanguage = tl.GetCookie("CurrentLanguage");
        var loadText = ToolLanguage.Loading[currentLanguage]; // "Loading, please wait...";
        //                if (undefined != waitingText) {
        //                    loadText = waitingText;
        //                }

        if (!Tool._loading)
          $(document.body).append(
            '<div style="position:fixed; left:50%; top:50%; width:144px; height:90px; margin:-45px 0 0 -112px; padding-left:80px; line-height:90px; overflow:hidden; background:#fff url(//pic.c-ctrip.com/ebooking/web/loading_50.gif) no-repeat 15px center; border-radius:10px;" id="loading">' +
              loadText +
              "</div>",
          );
        Tool._loading = Tool._loading || $("#loading");
        Tool._loading.show();
        msg && Tool._loading.text(msg);
        $.mask(Tool._loading);
      }, 200);
      return timer;
    },
    //隐藏正在加载进度条
    HideLoad: function (timer) {
      clearTimeout(timer);
      if (Tool._loading) {
        $.unmask(Tool._loading);
        Tool._loading.hide();
      }
    },
    //全角转半角
    C2H: function (str) {
      var result = "";
      for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) == 12288) {
          result += String.fromCharCode(str.charCodeAt(i) - 12256);
        } else if (str.charCodeAt(i) > 65280 && str.charCodeAt(i) < 65375) {
          result += String.fromCharCode(str.charCodeAt(i) - 65248);
        } else result += String.fromCharCode(str.charCodeAt(i));
      }
      return result;
    },
    O2String: function (O) {
      var S = [];
      var J = "";
      if (Object.prototype.toString.apply(O) === "[object Array]") {
        for (var i = 0; i < O.length; i++) S.push(this.O2String(O[i]));
        J = "[" + S.join(",") + "]";
      } else if (Object.prototype.toString.apply(O) === "[object Date]") {
        J = "new Date(" + O.getTime() + ")";
      } else if (
        Object.prototype.toString.apply(O) === "[object RegExp]" ||
        Object.prototype.toString.apply(O) === "[object Function]"
      ) {
        J = O.toString();
      } else if (Object.prototype.toString.apply(O) === "[object Object]") {
        for (var i in O) {
          var str =
            typeof O[i] == "string"
              ? '"' + O[i].replace(/"/g, "“").replace(/\\/g, "\\\\") + '"'
              : typeof O[i] === "object"
                ? this.O2String(O[i])
                : O[i];
          S.push(i + ":" + str);
        }
        J = "{" + S.join(",") + "}";
      }

      return J;
    },
    DateDiff: function (d1, d2) {
      var day = 24 * 60 * 60 * 1000;
      var checkTime = d1.getTime();
      var checkTime2 = d2.getTime();
      return (checkTime - checkTime2) / day;
    },
    ConvertStr2Date: function (d) {
      var dateArr = d.split("-");
      return new Date(dateArr[0], dateArr[1] - 1, dateArr[2]);
    },
    GetCookie: function (objName) {
      var arrStr = document.cookie.split("; ");
      for (var i = 0; i < arrStr.length; i++) {
        var temp = arrStr[i].split("=");
        if (temp[0] == objName) return unescape(temp[1]);
      }
    },
    SetCookie: function (c_name, value, expiredays) {
      var exdate = new Date();
      exdate.setDate(exdate.getDate() + expiredays);
      document.cookie =
        c_name +
        "=" +
        escape(value) +
        (expiredays == null ? "" : "; expires=" + exdate.toGMTString()) +
        ";path=/";
    },
    DelCookie: function (name) {
      var exp = new Date();
      exp.setTime(exp.getTime() - 1);
      document.cookie = name + "=N;expires=" + exp.toGMTString() + ";path=/";
    },
    GetQueryString: function (name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    // 对Date的扩展，将 Date 转化为指定格式的String 例子：
    // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
    // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
    FormatDate: function (date, fmt) {
      var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        S: date.getMilliseconds(), //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length),
        );
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length),
          );
      return fmt;
    },

    IsDate: function (value) {
      var rs = false;
      if (value.length != 0) {
        var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/;
        var r = value.match(reg);
        if (r != null) {
          rs = true;
        }
      }
      return rs;
    },

    TranslateByCommonRes: function (inputString) {
      var outputString = "";
      try {
        outputString = inputString.replace(
          /{[A-Z]{1}[^}]*}/g,
          function (match) {
            var spIndex = match.indexOf(" ");
            var key = match.substr(1, spIndex).replace(":", "_");
            var multiText = "";
            if (window.CommonMultiLanguageResource) {
              multiText = window.CommonMultiLanguageResource[key];
            }

            if (multiText && multiText.length > 0) {
              return multiText;
            } else {
              return match.substr(spIndex, match.length - 1);
            }
          },
        );
      } catch (err) {}
      return outputString;
    },

    Translate: function (inputString) {
      var outputString = "";
      try {
        outputString = inputString.replace(
          /{[A-Z]{1}[^}]*}/g,
          function (match) {
            var spIndex = match.indexOf(" ");
            var key = match.substr(1, spIndex).replace(":", "_");
            var multiText = "";
            if (window.MultiLanguageResource) {
              multiText = window.MultiLanguageResource[key];
            }

            if (multiText && multiText.length > 0) {
              return multiText;
            } else {
              return match.substr(spIndex, match.length - 1);
            }
          },
        );
      } catch (err) {}
      return outputString;
    },

    StopPropagation: function (e) {
      e = e || window.event;
      if (e.stopPropagation) {
        e.stopPropagation();
      } else {
        e.cancelBubble = true;
      }
    },
    sleep: function (n) {
      //n表示的毫秒数
      var start = new Date().getTime();
      while (true) if (new Date().getTime() - start > n) break;
    },

    xAjax: function (options) {
      var self = this,
        reqTime = new Date().getTime();

      var callbackName = (function () {
        var base = "qwertyuiopasdfg$hjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
        var r = "";
        for (var i = 0; i < 10; i++) {
          r += base.charAt(~~(Math.random() * base.length));
        }
        return r;
      })();

      var key = "";
      window[callbackName] = function (gen) {
        delete window[callbackName];
        if (window.signature) {
          key = window.signature(options);
        } else {
          if ($.isFunction(gen)) {
            key = gen();
          } else {
            key = gen;
          }
        }
        var hoteluuidkeys = window.Kar98k ? window.Kar98k.hoteluuidkeys : "";

        if (options.data) {
          var json = JSON.parse(options.data);
          json.spiderkey = key;
          json.hoteluuidkeys = hoteluuidkeys;
          if (window.signature) {
            json.spiderVersion = "2.0";
          }
          options.data = JSON.stringify(json);
        } else {
          if (window.signature) {
            options.data = JSON.stringify({
              spiderkey: key,
              hoteluuidkeys: hoteluuidkeys,
              spiderVersion: "2.0",
            });
          } else {
            options.data = JSON.stringify({
              spiderkey: key,
              hoteluuidkeys: hoteluuidkeys,
            });
          }
        }

        if (options.success) {
          var _success = options.success;
          options.success = function (resp) {
            self.spiderRedirectProcess(resp);
            resp.reqTime = reqTime;
            _success(resp);
          };
        } else {
          options.success = self.spiderRedirectProcess;
        }

        $.ajax(options);
      };

      // 开启新版反爬
      if (window.signature) {
        if ($.isFunction(window[callbackName])) {
          eval(window[callbackName](""));
        }
      } else {
        var finish = self.getSkey(callbackName);
        if (finish) {
          return;
        }

        // 老版指纹获取
        $.ajax({
          url: "/ebkovsassembly/api/spider/getSpiderKey?v=" + Math.random(),
          cache: false,
          data: callbackName,
          type: "POST",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          timeout: 120000,
          success: function (data) {
            //执行反爬返回的script
            if (200 == data.code && data.data && data.data.length > 0) {
              try {
                eval(data.data);
              } catch (e) {
                console.error(e);
              }
            } else {
              if ($.isFunction(window[callbackName])) {
                window[callbackName]("");
              }
            }
          },
          error: function (e) {
            if ($.isFunction(window[callbackName])) {
              window[callbackName]("");
            }
          },
        });
      }
    },
    getSkey: function (callbackName) {
      var keySet = sf.entries && sf.entries().next().value;
      var r = false;
      if (keySet) {
        var k = keySet[0],
          v = keySet[1];
        sf.delete(k);
        if (v != null) {
          if ($.isFunction(window[callbackName])) {
            window[callbackName](v);
          }
        } else {
          document.addEventListener(
            k,
            function (event) {
              if ($.isFunction(window[callbackName])) {
                window[callbackName](event.detail.value);
              }
            },
            { capture: false, once: true },
          );
        }
        r = true;
      }
      return r;
    },
    initKeyPool: function (poolSize) {
      var self = this;
      for (var i = 0; i < poolSize; i++) {
        self.preloadSpiderKey();
      }
    },
    preloadSpiderKey: function () {
      var callbackName = (function () {
        var base = "qwertyuiopasdfg$hjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
        var r = "";
        for (var i = 0; i < 10; i++) {
          r += base.charAt(~~(Math.random() * base.length));
        }
        return r;
      })();
      var key = "";
      sf.set(callbackName, null);
      window[callbackName] = function (gen) {
        delete window[callbackName];
        var key;
        if ($.isFunction(gen)) {
          key = gen();
        } else {
          key = gen;
        }
        if (sf.has(callbackName)) sf.set(callbackName, key);
        document.dispatchEvent(
          new CustomEvent(callbackName, { detail: { value: key } }),
        );
      };
      $.ajax({
        url: "/ebkovsassembly/api/spider/getSpiderKey?v=" + Math.random(),
        cache: false,
        data: callbackName,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        timeout: 500,
        success: function (data) {
          //执行反爬返回的script
          if (200 == data.code && data.data && data.data.length > 0) {
            try {
              eval(data.data);
            } catch (e) {
              console.error(e);
            }
          } else {
            if ($.isFunction(window[callbackName])) {
              window[callbackName]("");
            }
          }
        },
        error: function (e) {
          if ($.isFunction(window[callbackName])) {
            window[callbackName]("");
          }
        },
      });
    },
    spiderRedirectProcess: function (resp) {
      var self = this;
      if (resp) {
        if (resp.code == 2100) {
          self.redirectSpiderPage();
        } else if (resp.code == 2101) {
          self.showJigsawVerification();
        }
      }
    },
    showJigsawVerification: function () {
      var self = this;
      if (window.slidObj) {
        // window.slidObj.clear();//如果涉及在同一个div多次渲染验证码，可以加个判断来清除
        return;
      }
      window.slidObj = new jigsawVerification({
        id: "verification-code", // 验证码div的id
        appId: 100012428, // 申请的appId值
        containerId: "slider-container", // 验证码div的父元素id值
        businessSite: "ebk_antibot_online_pic", // 申请的businessSite值
        width: "280px", // 验证码div宽度,高度是根据宽度变化的，有比例关系
        language: self.convertLan(), // 滑块验证码语种
        // 状态监听函数
        stateChange: function (state) {
          if (state === 1 || state === 0) {
            $("#slider-container").show();
          } else if (state == 2) {
            $("#slider-container").hide();
          }
        },
        // 拼图错误后调用的函数
        onJigsawFail: function () {},
        // 选图标错误后调用的函数
        onSelectFail: function () {},
        // 风险检测结果
        resultHandler: function (e) {
          // console.log("token:", e.token, 'e.checkState:', e.checkState, 'e.version', e.version, "rid:", e.rid);
          self.verifySpider(e.token);
        },
      });
    },
    convertLan: function () {
      var lan = "zh-CN";
      if (!usertrace || !usertrace.language) {
        return lan;
      }
      switch (usertrace.language) {
        case "zh-CN":
          lan = "zh-CN";
          break;
        case "zh-HK":
        case "zh-TW":
          lan = "zh-HK";
          break;
        case "ja-JP":
          lan = "ja-JP";
          break;
        case "ko-KR":
        case "th-TH":
        case "en-US":
        default:
          lan = "en-US";
          break;
      }
      return lan;
    },
    verifySpider: function (token) {
      var self = this;
      $.ajax({
        url: "/ebkovsassembly/api/spider/verify?v=" + Math.random(),
        cache: false,
        data: JSON.stringify({ stoken: token }),
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        timeout: 5000,
        success: function (data) {
          //执行反爬返回的script
          if (data && 200 == data.code) {
            window.location.refresh();
          } else {
            self.redirectSpiderPage();
          }
        },
        error: function (e) {
          //self.redirectSpiderPage();
        },
      });
    },
    redirectSpiderPage: function () {
      window.location.href = "/ebkovsassembly/spider";
    },
    changeURLArg: function (url, arg, arg_val) {
      var pattern = arg + "=([^&]*)";
      var replaceText = arg + "=" + arg_val;
      if (url.match(pattern)) {
        var tmp = "/(" + arg + "=)([^&]*)/gi";
        tmp = url.replace(eval(tmp), replaceText);
        return tmp;
      } else {
        if (url.match("[?]")) {
          return url + "&" + replaceText;
        } else {
          return url + "?" + replaceText;
        }
      }
    },
    loadNewSignature() {
      var self = this;
      // 加载新版反爬指纹JS
      // window.handleInvokePlugin('HESDTSource', (HEResourceElement) => {
      //     // 在回调函数中可获取window.signature
      //     if (window.signature) {
      //         console.log("window signature: is open");
      //     } else {
      //         // 新版加载失败，需要使用以前的预加载机制
      //         this.initKeyPool(2);
      //     }
      // });
    },
  };

  window.ebkalert = function (text, onclose) {
    function _creatHtml() {
      $("#ebkalertContainer").remove();
      var $alertContainer = $(
        '<div class="ebk3-modwin ebk3-alert ebk3-simple-alert order-alert" id="ebkalertContainer">' +
          '<a href="javascript:" class="ebk3-close" id="closeAlert">×</a>' +
          "</div>",
      );
      var $textContainer = $('<div class="ebk3-alert-cont"></div>');
      $textContainer.append(
        $('<span class="ebk3-alert-text"> ' + text + "</span>"),
      );
      $textContainer.append(
        "<div><input type='button' id='btnCloseAlert' class='btn btn-query' value='" +
          GetPagerLanguage("关闭") +
          "'></div>",
      );

      $("body").append($alertContainer.append($textContainer));
    }

    function _bindEvent() {
      $("#closeAlert").bind("click", function () {
        _hide();
      });
      $("#btnCloseAlert").bind("click", function () {
        _hide();
      });
    }

    function _show() {
      var popWindow = { el: $("#ebkalertContainer") };
      maskShow(popWindow.el, true);
      $("body").css("overflow-y", "hidden");
      $("body").css("overflow-x", "hidden");
      $("#mask_show_div").css("width", $("#mask_show_div").width() + 20 + "px");
    }

    function _hide() {
      maskShow(null);
      if (onclose) {
        onclose();
      }
    }

    _creatHtml();
    _bindEvent();
    _show();
  };

  var tl = (w.tl = new Tool());
})(window);

var ToolLanguage = {
  Loading: {
    SimpChinese: "加载中，请稍候...",
    TraditionalChinese: "加載中，請稍候...",
    English: "Loading, please wait...",
    Japanese: "ロード中、しばらくお待ちください...",
    Korean: "로딩 중 잠시만 기다리십시오...",
  },
};

window.TimeZone2Local = function (d, format) {
  var localOffset_M = new Date().getTimezoneOffset();
  if (localOffset_M == undefined) return d;

  if (localOffset_M == 0 && window.ebkbasedata && !window.ebkbasedata.isoversea)
    return d;

  var localOffset = localOffset_M * 60000;

  if (d == undefined) {
    return d;
  }

  d = d.replace(/-/g, "/");

  var date = new Date(d);

  if (date == "Invalid Date") {
    return d;
  }

  if (format == undefined) {
    format = "yyyy-MM-dd";
  }

  //var serverTime = new Date(2017,5,1,8,0,0).getTime();
  var serverTime = date.getTime();

  //北京时间 2 utc
  var utc = serverTime - 480 * 60000;

  localTime = utc - localOffset;

  nd = new Date(localTime);

  //document.writeln("Hawaii time is " + nd.Format(format) + "<br>");
  return nd.Format(format);
};
